package top.yinjinbiao.mqtt.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import top.yinjinbiao.mqtt.client.CustomMqttClient;
import top.yinjinbiao.mqtt.consts.WebSocketConstant;
import top.yinjinbiao.mqtt.enums.QosEnums;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @Description
 * @Author yin.jinbiao
 * @Date 2021/11/23 16:40
 * @Version 1.0
 */
@Component
@Slf4j
public class TestWebSocketHandler extends TextWebSocketHandler {

    @Autowired
    private CustomMqttClient customMqttClient;

    @Override
    public void afterConnectionEstablished(WebSocketSession session)   {
        synchronized (TestWebSocketHandler.class){
            WebSocketConstant.websocketClients.get("WATER_LEVEL").add(session);
            log.info("websocket client = {} 加入。",session);
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status)   {
        synchronized (TestWebSocketHandler.class){
            WebSocketConstant.websocketClients.get("WATER_LEVEL").remove(session);
            log.info("websocket client = {} 关闭。",session);
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception)   {
        synchronized (TestWebSocketHandler.class){
            WebSocketConstant.websocketClients.get("WATER_LEVEL").remove(session);
            log.info("websocket client = {} 传输错误，关闭连接。",session);
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) {
        // 解析 message 的内容，调用 client 对相应的 topic 发送对应数据，达到控制设备的目的。
        log.info("websocket 服务端收到消息，message = {} .", message);
        customMqttClient.publish("testtopic/123"," public msg :"+ LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME), QosEnums.QoS2,false);
    }

}
